import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import styled from "styled-components";
import { CloseCircleOutlined } from '@ant-design/icons';
import { useSearchParams } from "@/router/hooks";
import { useSettingActions, useSettings } from "@/store/settingStore";
import { useCacheMenus, useMenuActions, useMicroMenuData } from "@/store/menuStore";
import { ConfigProvider, Menu } from "antd";
import microApp from '@micro-zoe/micro-app'

const getDevUrl = (url) => {
  let urlObj = new URL(url)
  let devLs = import.meta.env.VITE_APP_XIANWAANG.split(',')
  if (devLs.find((s) => url.includes(s))) {
    return location.origin + urlObj.pathname
  }
  return url
}

const MicroRightWrapper = (props, ref) => {
  const searchParams = useSearchParams()
  const settings = useSettings();
  const { setSettings } = useSettingActions()
  const showRightSidebar = settings.showRightSidebar
  const microMenus = useMicroMenuData()
  let cacheMenus = useCacheMenus();
  const { setCacheMenus } = useMenuActions()
  const [menus, setMenus] = useState([...microMenus])
  const [activeData, setActiveData] = useState()

  useImperativeHandle(ref, () => ({
    setMicroApp: (data) => {
      setMicroApp(data)
    }
  }));

  const activeUrl = useMemo(() => {
    if (activeData && import.meta.env.MODE === 'development') {
      return getDevUrl(activeData.url)
    }
    return activeData?.url
  }, [activeData])

  const cacheCodes = useMemo(() => {
    return cacheMenus.map(item => item.code)
  }, [cacheMenus])

  const menuList = useMemo(() => {
    return menus.map((d) => {
      return {
        key: d.code,
        label: <>{d.appName}<CloseBtn style={{ display: activeData?.code !== d.code && cacheCodes.includes(d.code) ? 'block' : 'none' }} onClick={(e) => uninstallApp(e, d)}><CloseCircleOutlined /></CloseBtn></>,
      }
    })
  }, [menus, cacheCodes, activeData])

  const appInfo = useMemo(() => {
    return menus.find(item => item.code === activeData?.code)
  }, [menus, activeData])

  useEffect(() => {
    let rightMicroApp;
    searchParams.forEach((value, key) => {
      if (key.includes('micro-app--')) {
        rightMicroApp = {
          code: key.replace('micro-app--', ''),
          url: value
        }
      }
    })
    if (rightMicroApp) {
      menus.forEach(d => {
        if (d.code === rightMicroApp.code) {
          setMicroApp(d)
        }
      })
    } else if (searchParams.get('menuUrl') || searchParams.get('menuCode')) {
      setMicroApp({
        code: searchParams.get('menuCode'),
        appCode: searchParams.get('menuCode'),
        url: searchParams.get('menuUrl'),
        appName: searchParams.get('menuName') || '',
        name: searchParams.get('menuName') || ''
      })
    }
  }, [])

  const uninstallApp = (e, data) => {
    e.stopPropagation()
    let options = cacheMenus.filter(d => d.code !== data.code)
    setCacheMenus(options)
    microApp.unmountApp('micro-app--' + data.code).then(() => {
      console.log('卸载成功')
    })
  }

  const setMicroApp = (data) => {
    if (!data) return
    let options = [...menus]
    let isData = options.find(d => d.code === data.code)

    console.log('isData', isData)
    if (isData) {
      setActiveData({ ...isData, url: getMenuUrlByCache(isData.code) || isData.url })
      setCacheMenu(isData)
    } else if (data.url) {
      isData = { ...data, code: data.code || new Date().getTime() + '' }
      options.push({ ...isData })
      setActiveData({ ...isData, url: getMenuUrlByCache(isData.code) || isData.url })
      setCacheMenu(isData)
      setMenus(options)
    }
  }
  const getMenuUrlByCache = (code) => {
    return cacheMenus.find(d => d.code === code)?.url
  }

  const setCacheMenu = (data) => {
    if (cacheMenus.some(d => d.code === data.code)) return
    setCacheMenus(cacheMenus.concat({ ...data }))
  }

  const sliderClose = () => {
    setSettings({
      ...settings,
      showRightSidebar: false
    })
  }
  const sliderOpen = () => {
    setSettings({
      ...settings,
      showRightSidebar: true
    })
  }

  const onMenuClick = (e) => {
    setMicroApp(menus.find(d => d.code === e.key))
  }

  const RightSidebar = () => {
    return (
      showRightSidebar ?
        <aside className="layout-slider">
          <div className='layout-slider-logo'>
            {appInfo?.appName || '应用集成管理'}
          </div>
          <div className='layout-slider-nav'>
            <ConfigProvider theme={{
              components: {
                Menu: {
                  itemBg: 'none',
                  itemColor: '#fff',
                  groupTitleColor: '#fff',
                  itemHoverColor: 'none',
                  itemSelectedColor: '#fff'
                }
              },
            }}>
              <Menu
                onClick={onMenuClick}
                selectedKeys={[activeData?.code]}
                items={menuList}
              />

            </ConfigProvider>
          </div>
          <div className='layout-slider-close' onClick={sliderClose}></div>
        </aside>
        : <div className='layout-slider-open' onClick={sliderOpen}></div>
    )
  }

  return <StyleWrap className="micro-right-wrapper" id="container-layout-wrapper">
    <RightSidebar />
    <div className="micro-app-wrapper layout-content" style={{ marginLeft: showRightSidebar ? '250px' : undefined }}>
      {!!activeData && <micro-app name={'micro-app--' + activeData.code} url={activeUrl} clear-data iframe></micro-app>}
    </div>
  </StyleWrap>;
}
const StyleWrap = styled.div`
  &.micro-right-wrapper {
    width: 50%;
    height: 100%;
    flex-shrink: 0;
    position: relative;
  }
  .micro-app-wrapper{
    overflow: auto;
    micro-app{
      min-width: 1200px;
    }
  }
`
const CloseBtn = styled.span`
position: absolute;
right: 0;
top: 0;
padding: 0 6px;
transition: all .3s;
color: #ffffff;
opacity: .5;
&:hover {
  opacity: 1;
  transform: scale(1.2);
}
`

export default forwardRef(MicroRightWrapper);